#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>

#define MAX_NUM 41

struct Student
{
	char ID[20];
	char name[30];
	int age;
	double score;
};

struct Student ST_data[MAX_NUM],ST_read[MAX_NUM];//define ST_data,ST_read as the struct Student

bool CreatFile(struct Student *data , int n)
{
	FILE *file;
	file=fopen("D:\\Info.dat","wb");
	/*
	Use wb to open the file , and the different
	types of data in ST_data can be all writed in
	at one time
	*/
	if(file==NULL)
	{
		perror("Failed to open file");
		return false;
	}
	size_t wflag=fwrite(data,sizeof(struct Student),n,file);
	fclose(file);
	return wflag==n;
}

bool ReadOut(struct Student *data, int *n) {
    FILE *file = fopen("D:\\Info.dat", "rb");
    if (file == NULL) {
        perror("Failed to open file");
        return false;
    }
    size_t rflag = fread(data, sizeof(struct Student), MAX_NUM, file);
    fclose(file);
    *n = (int)rflag;  // Update the number of students read
    return rflag > 0;
}
 
void Sort(struct Student *data, int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (data[i].score < data[j].score) {
                struct Student temp = data[i];
                data[i] = data[j];
                data[j] = temp;
            }
        }
    }
}
 
void PrintStudents(struct Student *data, int n) {
    for (int i = 0; i < n; i++) {
        printf("ID:%s,Name:%s,Age:%d,Score:%.2lf\n", data[i].ID, data[i].name, data[i].age, data[i].score);
    }
}

int main(){
	char bufferc;
	int cnt=0,ST_cnt=0;
	int n,i;
	printf("Enter the number of the students:\n");
	scanf("%d",&n);
	getchar();//read one '\n' from scanf
	for(i=0;i<n;i++)
	{
		printf("ID:\n");
		while((bufferc=getchar())!='\n')
		{
			ST_data[ST_cnt].ID[cnt]=bufferc;
			cnt++;
		}
		ST_data[ST_cnt].ID[cnt]='\0';
		//get an ID ended with '\n'
		cnt=0;
		printf("name:\n");
		while((bufferc=getchar())!='\n')
		{
			ST_data[ST_cnt].name[cnt]=bufferc;
			cnt++;
		}
		ST_data[ST_cnt].name[cnt]='\0';
		//get a name ended with '\n'
		cnt=0;
		printf("age and score:\n");
		scanf("%d%lf",&ST_data[ST_cnt].age,&ST_data[ST_cnt].score);
		getchar();
		ST_cnt++;
	}
	if(!CreatFile(ST_data,ST_cnt))
	{
		perror("Failed to CreatFile");
		return 1;
	}
	if(!ReadOut(ST_read,&ST_cnt))
	{
		perror("Failed to ReadOut");
		return 1;
	}
	PrintStudents(ST_read,ST_cnt);
	Sort(ST_read,ST_cnt);
	PrintStudents(ST_read,ST_cnt);
	return 0;
}